import React, { useEffect, useState, useRef } from 'react';
import { View, Text, TextInput, TouchableOpacity, Animated, Dimensions } from 'react-native';
import { AppStyles, AppColors, TextStyles } from '../theme/uiLib.config';
import { useAIStore } from '../store/ai';
import { useRouter } from 'expo-router';
import Icon from 'react-native-vector-icons/Ionicons';

const { width } = Dimensions.get('window');

const BindAccount = () => {
  const router = useRouter();
  const { playAudio, stopAudio } = useAIStore();
  const [phoneNumber, setPhoneNumber] = useState('');
  const [verificationCode, setVerificationCode] = useState(['', '', '', '']);
  const [isButtonDisabled, setIsButtonDisabled] = useState(false);
  const [countdown, setCountdown] = useState(30);
  const [showVerification, setShowVerification] = useState(false);
  const verificationInputRefs = [useRef<TextInput>(null), useRef<TextInput>(null), useRef<TextInput>(null), useRef<TextInput>(null)];
  
  // 添加动画值
  const phoneScreenPosition = useRef(new Animated.Value(0)).current;
  const verificationScreenPosition = useRef(new Animated.Value(width)).current;

  useEffect(() => {
    playAudio(require('../../assets/audio/input_num.mp3'));
    return () => {
      stopAudio();
    };
  }, []);

  const animateScreenTransition = () => {
    Animated.parallel([
      Animated.timing(phoneScreenPosition, {
        toValue: -width,
        duration: 300,
        useNativeDriver: true,
      }),
      Animated.timing(verificationScreenPosition, {
        toValue: 0,
        duration: 300,
        useNativeDriver: true,
      }),
    ]).start();
  };

  const handleSendCode = () => {
    if (phoneNumber) {
      // 如果正在播放音频，则停止播放
      stopAudio();

      setIsButtonDisabled(true);
      setCountdown(30);
      
      // 先执行动画，然后设置状态
      animateScreenTransition();
      setTimeout(() => {
        setShowVerification(true);
      }, 300);

      const timer = setInterval(() => {
        setCountdown(prev => {
          if (prev <= 1) {
            clearInterval(timer);
            setIsButtonDisabled(false);
            return 30;
          }
          return prev - 1;
        });
      }, 1000);

      verificationInputRefs[0].current?.focus();
    }
  };

  const handleVerificationCodeChange = (text: string, index: number) => {
    const newCode = [...verificationCode];
    newCode[index] = text.replace(/[^0-9]/g, '');
    setVerificationCode(newCode);

    if (text && index < 3) {
      verificationInputRefs[index + 1].current?.focus();
    } else if (index === 3) {
      // 输入完最后一个验证码后跳转到商户页面
      router.push('/MerchantList');
    }
  };

  return (
    <View style={[{ flex: 1 }, AppStyles.pagePadding]}>
      <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 34 }}>
        <TouchableOpacity onPress={() => router.back()} style={{ marginRight: 10 }}>
          <Icon name="chevron-back-outline" size={24} color={AppColors.secondary} />
        </TouchableOpacity>
      </View>

      <View style={{ flex: 1, position: 'relative' }}>
        {/* 手机号输入屏幕 */}
        <Animated.View 
          style={[
            { position: 'absolute', width: '100%' },
            { transform: [{ translateX: phoneScreenPosition }] }
          ]}
        >
          <View style={{ alignItems: 'center', marginTop: 30 }}>
            <Text style={{ fontSize: 24, textAlign: 'center', fontWeight: 'bold' }}>查询积分商户</Text>
          <View style={{ flexDirection: 'row', alignItems: 'center',justifyContent: 'center', marginTop: 4 }}>
          <Icon name="alert-circle" size={20} color={AppColors.grey20} />
          <Text style={{ fontSize: 16, textAlign: 'center' ,color: AppColors.grey20}}>可绑定全家人的积分账户哦！</Text>
          </View>
          
          </View>

          <View style={{ marginTop: 120 }}>
            <TextInput
              value={phoneNumber}
              onChangeText={(text) => {
                const formattedText = text.replace(/[^0-9]/g, '');
                if (formattedText.length <= 11) {
                  setPhoneNumber(formattedText.replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3'));
                }
              }}
              keyboardType="numeric"
              placeholder="请输入手机号"
              style={[AppStyles.textInputStyle, { fontSize: 24, width: '90%', height: 70, alignSelf: 'center' }]}
              maxLength={13}
            />
          </View>

          <View style={{ alignItems: 'center' }}>
            <TouchableOpacity
              style={{
                alignSelf: 'center',
                justifyContent: 'center',
                width: '60%',
                height: 50,
                backgroundColor: AppColors.primary,
                borderRadius: 24,
                marginTop: 60,
              }}
              onPress={handleSendCode}
              disabled={isButtonDisabled}
            >
              <Text style={[TextStyles.h3, { color: '#fff', textAlign: 'center' }]}>
                {isButtonDisabled ? `已发送(${countdown})` : '发 送 验 证 码'}
              </Text>
            </TouchableOpacity>
          </View>
        </Animated.View>

        {/* 验证码输入屏幕 */}
        <Animated.View 
          style={[
            { position: 'absolute', width: '100%' },
            { transform: [{ translateX: verificationScreenPosition }] }
          ]}
        >
          <View style={{ alignItems: 'center', marginTop: 30 }}>
            <Text style={{ fontSize: 24, textAlign: 'center', fontWeight: 'bold' }}>输入验证码</Text>
          </View>

          <View style={{ marginTop: 120, flexDirection: 'row', justifyContent: 'space-between', width: '86%', alignSelf: 'center' }}>
            {verificationCode.map((code, index) => (
              <TextInput
                key={index}
                ref={verificationInputRefs[index]}
                value={code}
                onChangeText={(text) => handleVerificationCodeChange(text, index)}
                keyboardType="numeric"
                maxLength={1}
                style={[AppStyles.textInputStyle, { fontSize: 24,  width: 56, borderRadius: 20 }]}
              />
            ))}
          </View>
        </Animated.View>
      </View>
    </View>
  );
};


export default BindAccount; 